<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="deptName"
              placeholder="请输入部门名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="questionOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="questionCategoryTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="问题" prop="questionContent">
            <el-input
                v-model="queryParams.questionContent"
                placeholder="请输入问题题目"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['question:question:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['question:question:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['question:question:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['question:question:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="问题分类" align="center" prop="categoryName"/>
          <el-table-column label="问题" show-overflow-tooltip align="center" prop="questionContent"/>
          <el-table-column label="答案" show-overflow-tooltip align="center" prop="questionAnswer"/>
          <el-table-column label="问题比重" align="center" prop="questionWeight"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                  text
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['question:question:edit']"
              >修改
              </el-button>
              <el-button
                  text
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['question:question:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改面试题管理对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="questionRef" :model="form" :rules="rules" label-width="80px">
      <!-- <el-form-item v-if="!form.categoryId" label="所属岗位" prop="sectorName">
          <el-input v-model="form.sectorName" @click="openSelectSector" readonly placeholder="请选择所属岗位"/>
        </el-form-item>
        <el-form-item label="问题分类" prop="categoryId">
          <el-select v-model="form.categoryId" @change="handleCategoryChange" placeholder="请输入问题分类">
            <el-option
                v-for="dict in categoryList"
                :key="dict.categoryId"
                :label="dict.categoryName"
                :value="dict.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="问题">
          <editor v-if="open" v-model="form.questionContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="答案">
          <editor v-if="open" v-model="form.questionAnswer" :min-height="192"/>
        </el-form-item>
        <el-form-item label="问题比重" prop="questionWeight">
          <el-input v-model="form.questionWeight" placeholder="请输入问题比重"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <sector-select v-if="openSelect" @submit="handleSelectSector" @close="openSelect = false" />
  </div>
</template>

<script setup name="Question">
import SectorSelect from "@/views/question/questionSector/comps/sectorSelect.vue";
import {listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion} from "@/api/question/question";
import { listAllQuestionCategory } from "@/api/question/QuestionCategory";
import {listQuestionTree} from "@/api/question/questionSector";

const {proxy} = getCurrentInstance();

const questionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 选择岗位
const openSelect = ref(false);
// 分类列表
const categoryList = ref([]);

const questionOptions = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    categoryName: null,
    questionContent: null,
    questionAnswer: null,
    questionWeight: null,
  },
  rules: {
    sectorName: [{ required: true, message: "所属岗位不能为空", trigger: "change" }],
    categoryId: [{ required: true, message: "问题分类不能为空", trigger: "change" }],
  }
});

const {queryParams, form, rules} = toRefs(data);

const currentNode = ref({});

/** 查询面试题管理列表 */
function getList() {
  loading.value = true;
  listQuestion(queryParams.value).then(response => {
    questionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    questionId: null,
    categoryId: null,
    categoryName: null,
    questionContent: '',
    questionAnswer: '',
    questionWeight: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    delFlag: null
  };
  proxy.resetForm("questionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.questionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  if (queryParams.value.categoryId) {
    form.value.categoryId = queryParams.value.categoryId;
    form.value.categoryName = currentNode.value.categoryName;
    form.value.sectorId = currentNode.value.sectorId;
    form.value.sectorName = currentNode.value.sectorName;
    open.value = true;
    title.value = "添加面试题管理";
  } else {
    proxy.$modal.msgError("请先选择二级分类");
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _questionId = row.questionId || ids.value
  getQuestion(_questionId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改面试题管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["questionRef"].validate(valid => {
    if (valid) {
      if (form.value.questionId != null) {
        updateQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _questionIds = row.questionId || ids.value;
  proxy.$modal.confirm('是否确认删除面试题管理编号为"' + _questionIds + '"的数据项？').then(function () {
    return delQuestion(_questionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('question/question/export', {
    ...queryParams.value
  }, `question_${new Date().getTime()}.xlsx`)
}

/** 加载类型 */
function loadCategory() {
  listAllQuestionCategory({sectorId: form.value.sectorId}).then(res => {
    if (res.code === 200) {
      categoryList.value = res.data;
    }
  }).catch(err => {
    categoryList.value = [];
  })
}

/** 打开岗位选择 */
function openSelectSector() {
  openSelect.value = true;
}

/** 确认选择 */
function handleSelectSector(rows) {
  if (rows && rows.length > 0) {
    if (rows.length > 1) {
      proxy.$modal.msgError("只能选择一个岗位");
      return
    }
    const row = rows[0];
    form.value.sectorId = row.sectorId;
    form.value.sectorName = row.sectorName;
    openSelect.value = false;
    loadCategory()
  } else {
    proxy.$modal.msgError("请选择一条岗位信息");
  }
}

/** 分类更改触发 */
function handleCategoryChange(target) {
  const matchArr = categoryList.value.filter(item => item.categoryId === target);
  if (matchArr && matchArr.length > 0) {
    form.value.categoryName = matchArr[0].categoryName;
  }
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 节点单击事件 */
function handleNodeClick(data, node) {
  if (node.level > 1) {
    queryParams.value.categoryId = data.id;
    handleQuery();
    currentNode.value.categoryId = data.id;
    currentNode.value.categoryName = data.label;
    if (node.parent && node.parent.data) {
      currentNode.value.sectorId = node.parent.data.id;
      currentNode.value.sectorName = node.parent.data.label;
    }
  } else {
    queryParams.value.categoryId = null;
  }
}

function getCategoryTree() {
  listQuestionTree().then(res => {
    if (res.code === 200) {
      questionOptions.value = res.data;
    }
  });
}

getCategoryTree();
getList();
</script>
